package com.wanghlme.day27.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter", urlPatterns = "/*", initParams = {
        @WebInitParam(name = "encode", value = "UTF-8")
})
public class EncodingFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(EncodingFilter.class.getName());
    private String encode = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("Encoding Filter Init Start");
        encode = filterConfig.getInitParameter("encode");
        logger.info("Encode is {}", encode);
        logger.info("Filter is {}", filterConfig.getFilterName());
        logger.info("Encoding Filter Init End");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("Encoding Filter Done Start");
        servletRequest.setCharacterEncoding(encode);
        servletResponse.setCharacterEncoding(encode);
//        servletResponse.setContentType("text/text;charset=" + encode);
        filterChain.doFilter(servletRequest, servletResponse);
        logger.info("Encoding Filter Done End");
    }

    @Override
    public void destroy() {
        logger.info("Encoding Filter Destroy Start");
        logger.debug("Encoding filter was Destroy");
        logger.info("Encoding Filter Destroy End");

    }
}